package example.demo.forkjoin;

import example.demo.bean.Student;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

public class ReturnTask extends RecursiveTask<List<Student>> {
    private final int startValue;
    private final int endValue;
    /*数据源*/
    private final List<?> list;
    private static final int MAX = 1;

    public ReturnTask(int startValue, int endValue, List<?> list) {
        this.startValue = startValue;
        this.endValue = endValue;
        this.list = list;
    }

    @Override
    protected List<Student> compute() {
        if (endValue - startValue <= MAX) {
            /*接收子任务的计算结果*/
            List<Student> studentList = new ArrayList<>(endValue - startValue + 1);
            for (int i = startValue; i <= endValue; i++) {
                Object o = list.get(i);
                studentList.add((Student) o);
            }
            System.out.println(Thread.currentThread().getName() + "====submit-task");
            //上交本线程的执行结果
            return studentList;
        } else {
            int mid = (startValue + this.endValue) / 2;
            ReturnTask subTask1 = new ReturnTask(startValue, mid, list);
            subTask1.fork();
            ReturnTask subTask2 = new ReturnTask(mid + 1, endValue, list);
            subTask2.fork();
            //获取线程上交执行的结果
            List<Student> join1 = subTask1.join();
            List<Student> join2 = subTask2.join();
            /*返回这个总任务的结果*/
            return join1.addAll(join2) ? join1 : new ArrayList<>();
        }
    }
}
